<template>
  <el-card shadow="hover" class="cardClass" :style="cssVars"  >
    <template #header>
      <div class="option-header">
        <div class="option-header-content"><span>上不封顶安全气囊</span></div>
        <div v-if="props.calcSuccess=='true'" class="option-header-content"><span style="color: #22bb98 ">计算成功</span></div>
<!--        <div v-if="props.calcSuccess=='false'" class="option-header-content"><span style="color: #e53c3c">计算失败</span></div>-->
        <div v-if="props.calcSuccess=='false'" class="option-header-content">
          <el-tooltip  effect="light"  >
            <template #content> <div style="width: 280px;">
              <span style="color: #e53c3c;">{{props.errorMsg}}</span>
            </div> </template>
            <span style="color: #e53c3c">计算失败</span>
          </el-tooltip>
        </div>
        <div>
          <el-button style="background: transparent;" :disabled="cpoyWait" v-if="props.useType=='calc'" class="delete" @click="copy" title="复制">
            <el-icon>
              <copy-document/>
            </el-icon>
          </el-button>
          <el-button style="background: transparent;" class="delete" @click="cancel" title="关闭">
            <el-icon>
              <circle-close/>
            </el-icon>
          </el-button>
        </div>
      </div>
    </template>

    <el-form ref="formRef" :disabled="form.data.readOnly" :model="form.data" label-width="auto" size="small"
             :rules="rules">
      <div class="optionst01">
        <el-form-item label="交易方向" prop="payDirection">
          <el-radio-group v-model="form.data.payDirection" size="small" :fill="getColor()">
            <el-radio-button label="1">买入</el-radio-button>
            <el-radio-button label="-1">卖出</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="标的" label-width="auto" prop="instrumentId">
          <Underlyer v-model="form.data.instrumentId" @change="onBlurInstrumentId" :underlyerId="form.data.instrumentId" :filterDate="true" ref="underlyerIdRef"/>
        </el-form-item>


        <el-form-item label="起始日" label-width="auto" prop="effectiveDate">
          <el-date-picker value-format="YYYY-MM-DD" v-model="form.data.effectiveDate" @blur="onBlurEffectiveDate" type="date" placeholder="">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="期限" label-width="auto" prop="term">
          <Numberinput maxlength="4" v-model="form.data.term" min="0" append="D"/>
        </el-form-item>

        <el-form-item label="到期日" label-width="auto" prop="terminationDate">
          <el-date-picker value-format="YYYY-MM-DD" v-model="form.data.terminationDate" type="date" placeholder=""/>
        </el-form-item>

        <el-form-item label="支付偏移" label-width="auto" prop="paymentDaysOffset">
          <Numberinput maxlength="4" v-model="form.data.paymentDaysOffset"  append="D"/>

        </el-form-item>

        <el-form-item label="支付日" label-width="auto" prop="terminationDate">
          <el-date-picker value-format="YYYY-MM-DD" v-model="form.data.terminationPaymentDate"
                          type="date"
                          placeholder=""/>
        </el-form-item>

        <el-form-item label="名义本金" prop="notional">
          <InputAmount maxlength="20" v-model="form.data.notional" append="元" precision="2"></InputAmount>
        </el-form-item>

        <el-form-item label="期初价格" label-width="auto" prop="spotPrice">
          <el-col :span="8">
            <el-checkbox name="status" false-label="0" true-label="1" v-model="form.data.priceOnWait">待定</el-checkbox>
          </el-col>
          <el-col :span="16">
            <InputAmount v-model:value="form.data.spotPrice" maxlength="20" :disabled="form.data.priceOnWait=='1'"
                         append="元" precision="2"/>
          </el-col>
        </el-form-item>

        <el-form-item label="交易数量" prop="optionEntitlement">
          <Numberinput v-model="form.data.optionEntitlement" precision="2" maxlength="20" :disabled="form.data.priceOnWait=='1'"  @blur="optionEntitlementChange"/>
        </el-form-item>
      </div>
      <!---------------------------------------------- 敲入结构---------------------------------------------------------->
      <div class="optionst02">
        <el-form-item label="敲入方向" prop='cbxTriggerType'>
          <dictCombox v-model="form.data.cbxTriggerType"
                      dictType="cbxTriggerType" disabled
                      :style="{width: '100%'}"></dictCombox>
        </el-form-item>
        <el-form-item label="敲入障碍价" prop="konckLevelPercentage" >
          <el-col :span="12">
            <Numberinput v-model="form.data.konckLevelPercentage"  precision="2" @blur="linkPercentage(form,form.data.konckLevelPercentage,form.data.spotPrice,'data.konckLevel')"  append="%"/>
          </el-col>
          <el-col :span="12">
            <Numberinput v-model=" form.data.konckLevel" @blur="linkPrice(form,form.data.konckLevel,form.data.spotPrice,'data.konckLevelPercentage')" precision="2" append="元"/>
          </el-col>
        </el-form-item>
        <el-form-item label="行权价" prop="strikePercentage">
          <el-col :span="12">
            <Numberinput v-model="form.data.strikePercentage"  precision="2"  @blur="linkPercentage(form,form.data.strikePercentage,form.data.spotPrice,'data.strike')"   append="%"/>
          </el-col>
          <el-col :span="12">
            <Numberinput v-model="form.data.strike" precision="2" maxlength="20" @blur="linkPrice(form,form.data.strike,form.data.spotPrice,'data.strikePercentage')" append="元"/>
          </el-col>
        </el-form-item>
        <el-form-item label="观察频率" prop='scheduleType'>
          <dictCombox v-model="form.data.scheduleType" filterKey="0,1"
                      dictType="scheduleType" ></dictCombox>
        </el-form-item>
        <el-form-item label="敲入参与率" prop="participationRate">
          <Numberinput v-model="form.data.participationRate" maxlength="20" precision="2" append="%"/>
        </el-form-item>

      </div>
      <div class="optionst01">
        <el-form-item label="未敲入参与率" prop="unTriggerParticipationRate">
          <Numberinput v-model="form.data.unTriggerParticipationRate" maxlength="20" precision="2" append="%"/>
        </el-form-item>
        <el-form-item label="未敲入行权价" prop="unTriggerStrikePercentage">
          <el-col :span="12">
            <Numberinput v-model="form.data.unTriggerStrikePercentage"  precision="2"  @blur="linkPercentage(form,form.data.unTriggerStrikePercentage,form.data.spotPrice,'data.unTriggerStrike')"   append="%"/>
          </el-col>
          <el-col :span="12">
            <Numberinput v-model="form.data.unTriggerStrike" precision="2" maxlength="20" @blur="linkPrice(form,form.data.unTriggerStrike,form.data.spotPrice,'data.unTriggerStrikePercentage')"/>
          </el-col>
        </el-form-item>
        <el-form-item label="是否年化">
          <dictCombox v-model="form.data.moneynessOption"
                      dictType="boolType"
                      :style="{width: '100%'}"></dictCombox>
        </el-form-item>
        <el-form-item v-show="form.data.moneynessOption>0" label="计息基准" prop="daycounter">
          <dictCombox v-model="form.data.daycounter" prop='disDayCount'
                      dictType="dayCounter"
                      :style="{width: '100%'}"></dictCombox>
        </el-form-item>
        <el-form-item class="operation">
          <el-button type="primary" @click="calc" v-show="props.useType=='calc'||props.useType=='scene'"
                     :disabled="form.data.priceOnWait=='1'">计算
          </el-button>
          <!--          <el-button @click="save2Trade" v-show="props.useType=='calc'">保存</el-button>-->
          <el-button @click="save2CalcLog" v-show="props.useType=='calc'" :disabled="form.data.priceOnWait=='1'">存为草稿</el-button>
        </el-form-item>
      </div>
    </el-form>
    <div class="optionst03">
      <PricingParam ref="PricingParamRef" :formData="form.data"  :valueDate="props.valueDate"  :index="props.index"
                    label-width="auto" :filterList="form.data.filterList" :disabled="form.data.readOnly"
                    :productType="productType" size="small"
                    :calcPricingParam="props.calcPricingParam"></PricingParam>
    </div>
    <!--  todo 情景因子  -->
    <!--  todo 结果  -->
    <div v-show="props.useType!='scene'">
      <singleResult ref="resultCompRef" :result="props.result" :index="props.index"
                    :calcMarketNpv="props.useType=='calc'"></singleResult>
    </div>
    <div v-if="props.useType!='scene'&&showVolRatesResult">
      <volRatesResult :calcMarketNpvResult="props.calcMarketNpvResult"/>
    </div>
  </el-card>
</template>

<script setup>
import {
  getCurrentInstance,
  onMounted,
  reactive,
  ref,
  watch,
  toRaw, nextTick
} from 'vue'
import Underlyer from '@/xquant/base/underlyer'
import Numberinput from '@/xquant/base/number'
import InputAmount from '@/xquant/base/InputAmount'
import dictCombox from '@/xquant/base/dictCombox'
import PricingParam from '@/views/calc/otcOtion/pricingparam/index'
import singleResult from '@/views/calc/otcOtion/result/single'
import volRatesResult from '@/views/calc/otcOtion/result/volRatesResult'
import {getTradeDay} from '@/utils/calc'
import {isVoid, isNotVoid} from '@/utils/util'
import {getTerminationPaymentDate} from '@/api/calc/otcOption/calc'
import {getOffset} from '@/api/calc/otcOption/calc'
import {debounce} from 'lodash'
import {setCommonSpotPrice} from '@/views/calc/otcOtion/instrument/common/common'
import {linkPercentage,linkPrice}  from '@/views/calc/otcOtion/instrument/common/formula'
import {formartFormP4, formartTableP2, formartFormP2, unFormartNumber, numberPrecision} from '@/utils/numberUtil'
import {validateDates} from "../common/validate";

const getColor = () => {
  return form.data.payDirection == '1' ? '#E53C3C' : '#22BB98'
}
const {proxy} = getCurrentInstance()
const productType = 'UncappedAirbag'
const cpoyWait = ref(false)
const labelWidth = ref('111px')
const showVolRatesResult = ref(false)
const form = reactive({
  data: {
    readOnly: false,
    productType: 'UncappedAirbag',
    payDirection: '1',
    instrumentId: null,
    optionType: 'Call',
    effectiveDate: proxy.$moment(new Date()).format('YYYY-MM-DD'),
    terminationDate: '',
    terminationPaymentDate: '',
    term: '30',
    paymentDaysOffset: '0',
    priceOnWait: '0',
    spotPrice: '',
    strikePercentage: '100',
    strike: 0,
    notional: '',
    optionEntitlement: '',
    moneynessOption: '1',
    daycounter: 'Actual/365',
    participationRate: 100,
    calendar: 'CHINA_EX',
    daycounterTerm: '365',
    isIncludeEndDate: '',
    endDate: '',
    isIncludeStartDate: '',
    startDate: '',
    cbxTriggerType:'Less',
    konckLevel:'',
    konckLevelPercentage:'100',
    unTriggerStrikePercentage:'',
    unTriggerStrike:'',
    scheduleType:'0',
    unTriggerParticipationRate:'100',
  },
  result: {},
  initFlag: ''
})
const rules = {
  payDirection: [{required: true, message: '请选择交易方向', trigger: 'change'}],
  instrumentId: [{required: true, message: ' ', trigger: 'change'}],
  optionType: [{required: true, message: '请选择涨跌类型', trigger: 'change'}],
  effectiveDate: [{required: true, message: ' ', trigger: 'change'}],
  terminationDate: [{required: true, message: ' ', trigger: 'change'}],
  term: [{required: true, message: ' ', trigger: 'change'}],
  paymentDaysOffset: [{required: true, message: ' ', trigger: 'change'}],
  notional: [{required: true, message: ' ', trigger: 'change'}, {
    validator: (rule, value, callback) => {
      return Number(value) > 0
    }, message: ' ', trigger: 'change'
  }],
  daycounter: [{required: true, message: ' ', trigger: 'change'}],
  daycounterTerm: [{required: true, message: ' ', trigger: 'change'}],
  spotPrice: [{required: true, message: ' ', trigger: 'change'}, {
    validator: (rule, value, callback) => {
      if (form.data.priceOnWait == '1') {
        return true
      }
      return Number(value) > 0
    }, message: ' ', trigger: 'change'
  }],
  optionEntitlement: [{required: true, message: ' ', trigger: 'change'}, {
    validator: (rule, value, callback) => {
      if (form.data.priceOnWait == '1') {
        return true
      }
      return Number(value) > 0
    }, message: ' ', trigger: 'change'
  }],
  strike: [{required: true, message: ' ', trigger: 'blur'}, {
    validator: (rule, value, callback) => {
      if (form.data.priceOnWait == '1') {
        return true
      }
      return Number(value) > 0
    }, message: ' ', trigger: 'change'
  }],
  strikePercentage: [{required: true, message: ' ', trigger: 'change'}, {
    validator: (rule, value, callback) => {
      if (form.data.priceOnWait == '1') {
        return true
      }
      return Number(value) > 0
    }, message: ' ', trigger: 'change'
  }],
  unTriggerStrikePercentage: [{required: true, message: ' ', trigger: 'change'}, {
    validator: (rule, value, callback) => {
      return Number(form.data.unTriggerStrikePercentage) > 0
    }, message: ' ', trigger: 'change'
  }],
  konckLevelPercentage: [{required: true, message: ' ', trigger: 'change'}, {
    validator: (rule, value, callback) => {
      return Number(form.data.konckLevelPercentage) > 0
    }, message: ' ', trigger: 'change'
  }],
  unTriggerParticipationRate: [{required: true, message: ' ', trigger: 'change'}],
  participationRate: [{required: true, message: ' ', trigger: 'change'}],
  paymentAmountPecentage: [{required: true, message: ' ', trigger: 'change'}],
  paymentAmount: [{required: true, message: ' ', trigger: 'change'}],
}
watch(() => form.data.priceOnWait, (nv, ov) => {
  if (form.data.priceOnWait == '1') {
    form.data.spotPrice = 0
  } else {
    setSpotPrice()
  }
})
/*
* 修改状态  false:当前没有操作  true:当前在被其他方法操作
* */
const lock = reactive({
  paymentDaysOffset: false,
  terminationPaymentDate: false,
})
watch(() => form.data.paymentDaysOffset, (nv, ov) => {
  if (nv === '') return
  if (lock.terminationPaymentDate) return
  lock.terminationPaymentDate = true
  onpaymentDaysOffsetChange()
})
const onpaymentDaysOffsetChange = debounce(function () {
  getTerminationPaymentDate({
    'calDay': form.data.terminationDate,
    'offset': form.data.paymentDaysOffset
  }).then(response => {
    lock.terminationPaymentDate = false
    if (response.errorCode != 0) {
    } else {
      form.data.terminationPaymentDate = response.result.CAL_DAY
    }
  })
}, 1000)
watch(() => form.data.terminationPaymentDate, (nv, ov) => {
  if (nv == ov || nv === '') return
  if (lock.paymentDaysOffset) return
  lock.paymentDaysOffset = true
  onterminationPaymentDate()
})
const onterminationPaymentDate = debounce(function (nv, ov) {
  getOffset({
    'day': form.data.terminationPaymentDate,
    'calDay': form.data.terminationDate
  }).then(response => {
    if (response.errorCode != 0) {

    } else {
      if (response.result == null) {
        onpaymentDaysOffsetChange()
        return
      }
      form.data.paymentDaysOffset = response.result.i
      lock.paymentDaysOffset = false
    }
  })
}, 1000)
onUnmounted(() => {
  // 移除组件时，取消定时器
  onpaymentDaysOffsetChange.cancel()
  onterminationPaymentDate.cancel()
})
const onBlurTerminationDate= (nv, ov) => {
  let a = proxy.$moment(form.data.terminationDate)
  let b = proxy.$moment(form.data.terminationPaymentDate)
  form.data.paymentDaysOffset = b.diff(a, 'days')
}
watch(() => [form.data.effectiveDate, form.data.terminationDate], ([nv, n2v], [ov, o2v]) => {
  if (!proxy.lsh.isEmpty(nv) && !proxy.lsh.isEmpty(n2v)) {
    let a = proxy.$moment(n2v)
    let b = proxy.$moment(nv)
    form.data.term = Number(a.diff(b, 'days'))
   proxy.$refs.PricingParamRef?proxy.$refs.PricingParamRef.calcRateByCode():''
  }
})

const onBlurEffectiveDate = () => {
  form.initFlag = false
  setSpotPrice()
}

watch(() => [form.data.term], ([newValue], [oldValue]) => {
  if (isNotVoid(String(form.data.effectiveDate)) && isNotVoid(String(newValue))) {
    let a = proxy.$moment(form.data.effectiveDate)
    form.data.terminationDate = a.add(newValue, 'days').format('YYYY-MM-DD')
    onpaymentDaysOffsetChange()
  }
})
// ------
watch(() => [form.data.notional, form.data.spotPrice], ([nv, n2v], [ov, o2v]) => {
  if (!proxy.lsh.isEmpty(nv) && !proxy.lsh.isEmpty(n2v)) {

    form.data.optionEntitlement = String(Number(nv) / Number(n2v))
  }
})

// ------
watch(() => [form.data.notional], ([newValue], [oldValue]) => {
  if (optionEntitlementLinkValid(newValue, form.data.spotPrice, form.data.optionEntitlement)) {
    return
  }
  if (isNotVoid(String(newValue))) {
    if (isNotVoid(String(form.data.spotPrice))) {
      form.data.optionEntitlement = proxy.lsh.divide(newValue, form.data.spotPrice).toFixed(4)
      return
    }
    if (isNotVoid(String(form.data.optionEntitlement))) {
      form.data.spotPrice = proxy.lsh.divide(newValue, form.data.optionEntitlement).toFixed(4)
      return
    }
  }
})
// ------
watch(() => [form.data.spotPrice], ([newValue], [oldValue]) => {
  if (optionEntitlementLinkValid(form.data.notional, newValue, form.data.optionEntitlement)) {
    return
  }
  if (isNotVoid(String(newValue))) {
    linkPercentage(form,form.data.strikePercentage,form.data.spotPrice,'data.strike')
    linkPercentage(form,form.data.unTriggerStrikePercentage,form.data.spotPrice,'data.unTriggerStrike')
    linkPercentage(form,form.data.konckLevelPercentage,form.data.spotPrice,'data.konckLevel')
    if (isNotVoid(String(form.data.notional))) {
      form.data.optionEntitlement = proxy.lsh.divide(form.data.notional, newValue)
      return
    }
    if (isNotVoid(String(form.data.optionEntitlement))) {
      form.data.notional = proxy.lsh.multiply(form.data.optionEntitlement, newValue).toFixed(4)
      return
    }
  }
})
// ------
const optionEntitlementChange = (newValue) => {
  if (form.data.priceOnWait == '1') return
  if (optionEntitlementLinkValid(form.data.notional, form.data.spotPrice, newValue)) {
    return
  }
  if (isNotVoid(String(newValue))) {
    if (isNotVoid(String(form.data.spotPrice))) {
      form.data.notional = proxy.lsh.multiply(newValue, form.data.spotPrice).toFixed(0)
      return
    }
    if (isNotVoid(String(form.data.notional))) {
      form.data.spotPrice = proxy.lsh.divide(form.data.notional, newValue).toFixed(4)
      return
    }
  }
}




function optionEntitlementLinkValid(notional, spotPrice, optionEntitlement) {
  if (Boolean(Number(notional)) && Boolean((Number(spotPrice))) && Boolean(Number(optionEntitlement))) {
    if (proxy.lsh.isEqual(optionEntitlement, proxy.lsh.divide(notional, spotPrice).toFixed(4))) {
      return true
    } else {
      return false
    }
  }
}

watch(() => [props.cfgId,form.data.instrumentId], ([newId, oldId]) => {
  getPricingCfg()
  setTimeout(() => {
    proxy.$refs.PricingParamRef?proxy.$refs.PricingParamRef.calcRateByCode():''
  }, 1000);
})

const onBlurInstrumentId = () => {
  setSpotPrice()
  getPricingCfg()
  setTimeout(() => {
    proxy.$refs.PricingParamRef?proxy.$refs.PricingParamRef.calcRateByCode():''
  }, 1000);
}
watch(() => props.valueDate, (newValue, oldValue) => {
  if (newValue != oldValue) {
    setSpotPrice()
    //触发修改定价参数的价格
    proxy.$refs.PricingParamRef.setSpotPrice({
      valueDate:props.valueDate,
      instrumentId:form.data.instrumentId
    })
   proxy.$refs.PricingParamRef?proxy.$refs.PricingParamRef.calcRateByCode():''
  }
})

const props = defineProps({
  calcMarketNpvResult: {
    type: Object,
    default: {}
  },
  /*是否为重放*/
  isReCalc: {
    type: Boolean,
    default: false
  },
  calcSuccess:{
    type: String,
    default: ''
  },
  errorMsg:{
    type: String,
    default: ''
  },
  useType: {
    type: String,
    default: 'calc'
  },
  index: {
    type: String,
    default: ''
  },
  del: {
    type: Function,
    default: null
  },
  copy: {
    type: Function,
    default: null
  },
  calc: {
    type: Function,
    default: null
  },
  marketNPV: {
    type: Function,
    default: null
  },
  save2Trade: {type: Function, default: null},
  save2CalcLog: {type: Function, default: null},
  getDefaultCfg: {
    type: Function,
    default: null
  },
  calcPricingParam: {
    type: Object,
    default: {}
  },
  result: {
    type: Object,
    default: {}
  },
  setformData: {
    type: Function,
    default: null
  },
  formData: {
    type: Object,
    default: null
  },
  cfgId: {type: String, default: ''},
  valueDate: {type: String, default: ''}
})
const getResult = () => {
  var data = []
  for (var item in props.result) {
    if (['npv', 'delta', 'gamma', 'vega', 'theta', 'rho', 'spotPrice', 'dscRate'].includes(item)) {
      data.push({
        key: item,
        val: proxy.lsh.ceil(props.result[item], 4)
      })
    }
  }
  return data
}

//定价参数
const getPricingCfg = async () => {
  let query = {
    'calcPricingParam': {
      'cfgId': props.cfgId
    },
    'instrument': {
      'productType': 'UncappedAirbag',
      'termsheet': {
        'underlyerIds': [form.data.instrumentId],
        'customLegs': [{
          'legId': 'leg01',
          'productType': 'UncappedAirbag'
        }
        ],
        'legs': [{
          'legId': 'leg01',
          'payDirection': form.data.payDirection
        }
        ]
      }
    }
  }
  //设置定价参数中的定盘价
  proxy.$refs.PricingParamRef.setSpotPrice({
    valueDate:props.valueDate,
    instrumentId:form.data.instrumentId
  })
  if (props.getDefaultCfg != null) {
    props.getDefaultCfg(query, props.index)
  }
}
const cancel = () => {
  props.del(props.index)
}
const copy = () => {
  props.copy(props.index)
  cpoyWait.value = true;
  setTimeout(() => {
    cpoyWait.value = false;
  }, 1000);
}
const calc = (flag) => {
  /*flag 标识 为All时单次计算不会提示成功或失败*/
  getInstrumentJson().then((res) => {
    if (Boolean(res)) {
      let otcOption = res.otcOption
      otcOption.calcInstrumentForm = res.calcInstrumentForm
      otcOption.calcPricingForm = res.calcPricingForm
      if (otcOption != '') {
        props.calc(otcOption, props.index, flag)
      }
      showVolRatesResult.value = false
    }
  })
}
const getInstrumentJson = async () => {
  return new Promise((resolve) => {
    proxy.$refs['formRef'].validate(valid => {
      if (valid) {
        validateDates(form)
        let calcPriceParam = getCalcPriceParam()
        let otcOption = {
          instrument: {
            'termsheet': {
              "notional": form.data.notional, // 名义本金
              "notionalCurrency": "CNY", // 名义本金币种
              "effectiveDate": form.data.effectiveDate, // 起始日
              "effectiveDateConv": "NONE",
              "terminationDate": form.data.terminationDate, // 到期日
              "terminationDateCalendar": form.data.calendar,
              "terminationDateConv": "NONE",
              "settlementType": "Cash", // 交割类型
              "settlementCurrency": "CNY", // 交割币种
              "underlyerIds": [
                form.data.instrumentId
              ],
              "calendars": [
                form.data.calendar
              ],
              "legs": [
                {
                  "legId": "leg01",
                  "payDirection": form.data.payDirection // 合约支付方向, 1:买入， -1：卖出
                }
              ],
              "customLegs": [
                {
                  "legId": "leg01",
                  "productType": "UncappedAirbag", // 产品类型：安全气囊 // 分为两个产品类型：上不封顶的Airbag期权、上端封顶的Airbag期权
                  "underlyers": [
                    {
                      "instrumentId": form.data.instrumentId, // 标的
                      "spotPrice": form.data.spotPrice, // 期初价格
                      "quoteType": "", // 定盘类型
                      "fixingDate": "", // 定盘日
                      "fixingDateConv": "Preceding",
                      "fixingDateCalendar": form.data.calendar
                    }
                  ],
                  "knock": {
                    "payDirection": form.data.payDirection, // 敲击方向
                    "trigger": {
                      "type":  "Less", // 障碍类型
                      "level": "", // 障碍价格
                      "levelPercentage": proxy.lsh.divide(form.data.konckLevelPercentage,100).toFixed(2) // 障碍价格百分比
                    },
                    "observeDates": {
                      "startDate": form.data.effectiveDate, // 观察开始日
                      "startDateConv": "NONE", // 观察开始日调整规则
                      "isIncludeStartDate": "0", // 是否包含观察开始日
                      "endDate": form.data.terminationDate, // 观察结束日
                      "endDateConv": "PRECEDING", // 观察结束日调整规则
                      "isIncludeEndDate": "1", // 是否包含观察结束日
                      "calendar": form.data.calendar, // 观察交易日历
                      "frequency": form.data.scheduleType=='1'?(form.data.scheduleType+"D"):"", // 观察频率
                      "discreteDates": [], // 离散观察日序列
                      "discreteDatesConv": "" // 离解观察日序列调整规则
                    },
                    "observeType": "Close", // 观察类型
                    "payStyle": "Deferred", // 支付类型，Immediate：立即支付 Deferred：到期支付
                    "calclationPeriod": {
                      "startDate": form.data.effectiveDate, // 计息开始日
                      "startDateConv": "FOLLOWING",
                      "isIncludeStartDate": "1",
                      "endDate": form.data.terminationDate, // 计息结束日
                      "endDateConv": "FOLLOWING",
                      "calendar": "CHINA_EX",
                      "isIncludeEndDate": "1"
                    },
                    "forward": { // 远期收益
                      "payDirection": "1", // 支付方向
                      "optionType": "Call", // 远期期权类型
                      "strike": "", // 行权价
                      "strikePercentage": proxy.lsh.divide(form.data.unTriggerStrikePercentage, 100).toFixed(2), // 行权价百分比
                      "daycounter": form.data.moneynessOption == '1' ? form.data.daycounter : '', // 计息基准

                      "upParticipationRate": "1", // 上涨参与率
                      "downParticipationRate": "1" // 下跌参与率
                    },
                    "minimumYields": [ // 敲入保底收益
                      {
                        "paymentAmount": "", // 金额
                        "paymentAmountPecentage": "", // 收益率
                        "daycounter": form.data.moneynessOption == '1' ? form.data.daycounter : '', // 计息基准
                        "participationRate": "1.0" // 参与率
                      }
                    ],
                  },
                  "unTrigger": {
                    "payDirection": form.data.payDirection, // 支付方向
                    "calclationPeriod": { // 计息区间
                      "startDate": form.data.effectiveDate, // 计息开始日
                      "startDateConv": "FOLLOWING",
                      "isIncludeStartDate": "1",
                      "endDate": form.data.terminationDate, // 计息结束日
                      "endDateConv": "FOLLOWING",
                      "calendar": form.data.calendar,
                      "isIncludeEndDate": "1"
                    },
                    "vanillaEuropean": {
                      "payDirection": "1", // 支付方向
                      "optionType": "Call", // 助推型价差期权类型
                      "strike": "", // 敲入行权价
                      "strikePercentage": proxy.lsh.divide(form.data.strikePercentage, 100).toFixed(2), // // 敲入行权价百分比
                      "daycounter": form.data.moneynessOption == '1' ? form.data.daycounter : '', // 计息基准
                      "participationRate": "1.0", // 参与率
                    },
                    "minimumYields": [ // 保底收益
                      {
                        "paymentAmount": "", // 金额
                        "paymentAmountPecentage": "", // 收益率
                        "daycounter": form.data.moneynessOption == '1' ? form.data.daycounter : '', // 计息基准
                        "participationRate": "" // 参与率
                      }
                    ]
                  },
                  "numberOfOptions": "1", // 期权份数
                  "optionEntitlement": "", // 标的数量,若为空则为N/S0
                  "fixingRounding": "5", // 定盘精度
                  "settlementPrecision": { // 结算精度
                    "type": "",
                    "OriginalReturn": "", // 收益率精度控制
                    "IncludingParticipationRate": "", // 含参与率精度控制
                    "IncludingAnnualAdjustment": "" // 含年化系数精度控制
                  },
                  "settlementDate": form.data.calendar, // 支付日
                  "settlementDateOffset": form.data.paymentDaysOffset+"D", // 支付日偏移量
                  "settlementDateConv": "NONE", // 支付日调整规则
                  "settlementDateCalendar": "CHINA_EX" // 支付日交易日历
                }
              ]
            },
            'productType': 'UncappedAirbag'
          },
          calcPricingParam: {
            valueDate: props.valueDate,
            cfgId: props.cfgId,
            calcPPCode: calcPriceParam.calcPPCode,
            underlyingPricingParams: [
              {
                underlyingID: form.data.instrumentId,
                dividend: calcPriceParam.dividend,
                volSurface: calcPriceParam.volSurface,
                funding: calcPriceParam.discount,
                spotPrice: calcPriceParam.spotPrice,
                spotQuoteType: calcPriceParam.spotQuoteType
              }
            ],
            discount: calcPriceParam.discount,
            customPricingParam: {}
          },
          underlyingMarkets: [
            {
              'underlyingID': form.data.instrumentId,
              'fixingPrices': [],
              'observerPrices': []
            }
          ]
        }
        let calcInstrumentForm = toRaw(form.data)
        let result = props.result
        let json = {
          otcOption: otcOption,
          calcInstrumentForm: calcInstrumentForm,
          calcPricingForm: calcPriceParam,
          calcResultForm: result
        }
        resolve(json)
      } else {
        resolve('')
      }
    })
  })
}
const save2Trade = () => {
  getInstrumentJson().then((res) => {
    if (Boolean(res)) {
      props.save2Trade(res, props.index)
    }
  })

}
const marketNPV = () => {
  getInstrumentJson().then((res) => {
    if (Boolean(res)) {
      showVolRatesResult.value = true
      let {otcOption} = res
      // proxy.$refs.resultCompRef.getNewNpv()
      res['instrument'] = otcOption.instrument
      res.otcOption.calcPricingParam['marketNPV'] = proxy.$refs.resultCompRef.getNewNpv()
      res['calcPricingParam'] = res.otcOption.calcPricingParam
      props.marketNPV(res, props.index)
    }
  })

}
const save2CalcLog = () => {
  getInstrumentJson().then((res) => {
    if (Boolean(res)) props.save2CalcLog(res, props.index)
  })

}
const getCalcPriceParam = () => {
  let calcPriceParam = proxy.$refs.PricingParamRef.getCalcPricingParam()
  return calcPriceParam
}

const getFormData = () => {
  return form
}
const setSpotPrice = () => {
  setCommonSpotPrice(proxy,form,props)
}
/*将proxy 暴露出去 给报价导出使用*/
defineExpose({
  calc, getPricingCfg, getCalcPriceParam, getFormData, getInstrumentJson,proxy
})
onMounted(() => {
  /*获取默认定价配置*/
  // getPricingCfg()
  /*获取预填表单*/

  // if (props.formData.data != null) {
  //   let a = Object.assign(form.data,props.formData)
  //   form.data = a;
  // }
  form.initFlag = props.isReCalc

  if (props.formData != null) {
    form.initFlag = isNotVoid(props.calcPricingParam)
    let data = props.formData.data || props.formData
    form.data = Object.assign(form.data, data)
  }
  // 这里获取DOM的value是旧值
  nextTick(()=>{
    form.initFlag = false
  })
})
watch(() => proxy.$attrs.disabled, (nv) => {
  form.data.readOnly = nv
}, {
  immediate: true
})
watch(()=>form,()=>{

  proxy.$attrs.cacheFormData()
},{deep:true})
</script>
<style scoped>
.cardClass {
  /*border-color: v-bind(color.value);*/
  width: 350px;
}
</style>

